//
// Created by martin on 7/7/21.
//


#include "session.h"
#include "ftpServer.h"

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#define DEFAULT_ROOT_DIR   "/home/martin"

/**
 * 创建会话
 */
session_t *session_create(int ctrlconn_sockfd)
{
    session_t *pses = (session_t *) malloc(sizeof(session_t));
    if (pses == NULL) { /* 创建session失败: 内存不够 */
        perror("session_create error");
        exit(1);
    }

    bzero(pses, sizeof(session_t));
    pses->ctrlconn_sockfd = ctrlconn_sockfd;
    pses->uid = -1; /* uid = 0是root用户, 因此0不能作为当前会话默认账户 */

    /* 设置root目录 */
    strcpy(pses->root_dir, DEFAULT_ROOT_DIR);

    /* 当前工作目录为root目录 */
    strcpy(pses->cur_work_dir, pses->root_dir);

    time(&pses->ctrlconn_refreshtime);

    return pses;
}

/**
 * 请求关闭session
 * @note 关闭session后， 会关闭数据连接和控制连接，不再接收用户FTP命令
 */
void session_close(session_t *pses)
{
    if (pses == NULL) return;

    pses->close = 1;
}

/**
 * 释放session资源
 */
void session_destroy(session_t *pses)
{
    if (pses != NULL) {
        if (pses->dataconn_sockfd > 0)
            close(pses->dataconn_sockfd);
//        if (pses->ctrlconn_sockfd > 0)
//            close(pses->ctrlconn_sockfd);

        free(pses);
    }
}

/**
 * 检查当前会话是否登录
 */
int session_checkloginstat(session_t *pses)
{
    if (pses == NULL) return -1;

    if (pses->uid < 0) {
        return -1;
    }

    return 0;
}


/**
 * 关闭数据连接
 */
int session_close_dataconn(session_t *pses)
{
    if (pses == NULL) return -1;

    if (pses->dataconn_sockfd > 0) {
        close(pses->dataconn_sockfd);
        pses->dataconn_sockfd = 0;
    }

    return 0;
}